package com.joesem.sale.client.logic.workOrder

import android.annotation.SuppressLint
import android.app.Activity
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import androidx.core.widget.addTextChangedListener
import com.bumptech.glide.Glide
import com.goodPermission.expansion.launchCamera
import com.goodPermission.expansion.launchPic
import com.google.gson.Gson
import com.jiaxing.sale.client.R
import com.jiaxing.sale.client.databinding.*
import com.joesem.sale.client.base.*
import com.joesem.sale.client.logic.workOrder.option.*
import com.joesem.sale.client.logic.workOrder.viewModel.OrderCreateViewModel
import com.joesem.sale.client.network.data.*
import com.joesem.sale.client.utils.click
import com.joesem.sale.client.widget.dialog.optionDatePickerSingle
import com.joesem.sale.client.widget.dialog.optionDeptUser
import com.joesem.sale.client.widget.dialog.optionMultipleDeptUser
import com.joesem.sale.client.widget.dialog.picDialog

@SuppressLint("SetTextI18n")
class WorkOrderCreateActivity : BaseActivity<ActivityWorkOrderCreateBinding>() {
    private val viewModel by createViewModel<OrderCreateViewModel>()
    private val selectedProducts = arrayListOf<ProductMode>()
    private val selectedImage = arrayListOf<UploadImgMode>()
    private val selectedCollaboration = arrayListOf<DeptUserMode>()
    private val orderValue = HashMap<String, Any?>()
    override fun LayoutToolbarBinding.toolbar(savedInstanceState: Bundle?) {
        visible()
        toolbarTitle.text = "创建工单"
        toolbarTheme()
    }

    override fun ActivityWorkOrderCreateBinding.initView(savedInstanceState: Bundle?) {
        try {
            intent.getStringExtra("eventData")?.let {
                Log.i("打印", "事件数据: $it")
                if (it.isNotEmpty()) {
                    Gson().fromJson(it, EventDetailsMode::class.java).let {
                        defaultEventDate(it)
                    }
                }
            }
        } catch (e: Exception) {
            make("事件数据有误：$e")
        }

        intent.getStringExtra("type")?.let {
            orderValue["type"] = it
        }
    }

    override fun ActivityWorkOrderCreateBinding.initListener() {
        btnCustomerAdd.click {
            optionCustomer(R.id.flCheckContent, supportFragmentManager) {
                orderValue["customer_id"] = it.id
                orderValue["county_id"] = it.user?.county_id
                orderValue["city_id"] = it.user?.city_id
                orderValue["province_id"] = it.user?.province_id
                tvCustomer.text = it.name.orEmpty()
                tvCustomer.setCompoundDrawablesRelativeWithIntrinsicBounds(null, null, null, null)
                llCustomerContent.visible()
                tvCustomerName.setText(it.user?.name.orEmpty())
                tvCustomerTelephone.setText(it.user?.phone.orEmpty())
                tvCustomerArea.text =
                    "${it.user?.province_name.orEmpty()}${it.user?.city_name.orEmpty()}${it.user?.county_name.orEmpty()}".ifEmpty { "" }
                tvCustomerAddress.setText(it.user?.detail_address.orEmpty())
            }
        }
        btnCreateCustomer.click {
            optionCreateCustomer(this@WorkOrderCreateActivity) {
                orderValue["customer_id"] = it.id
                orderValue["county_id"] = it.county_id
                orderValue["city_id"] = it.city_id
                orderValue["province_id"] = it.province_id
                tvCustomer.text = it.name.orEmpty()

                tvCustomer.setCompoundDrawablesRelativeWithIntrinsicBounds(null, null, null, null)
                llCustomerContent.visible()
                tvCustomerArea.text =
                    "${it.province_name.orEmpty()}${it.city_name.orEmpty()}${it.county_name.orEmpty()}".ifEmpty { "" }
                tvCustomerAddress.setText(it.detail_address.orEmpty())
            }
        }
        tvCustomerName.addTextChangedListener {
            orderValue["contact_name"] = it.toString()
        }
        btnCreateContact.click {
            if (orderValue["customer_id"] != null) {
                optionCreateContact(
                    this@WorkOrderCreateActivity,
                    orderValue["customer_id"]?.toString()?.toIntOrNull() ?: -1,
                    tvCustomer.text.toString()
                ) {
                    orderValue["county_id"] = it.county_id
                    orderValue["city_id"] = it.city_id
                    orderValue["province_id"] = it.province_id
                    tvCustomerName.setText(it.name.orEmpty())
                    tvCustomerTelephone.setText(it.phone.orEmpty())
                    tvCustomerArea.text =
                        "${it.province_name.orEmpty()}${it.city_name.orEmpty()}${it.county_name.orEmpty()}".ifEmpty { "" }
                    tvCustomerAddress.setText(it.detail_address.orEmpty())
                }
            } else {
                btnCustomerAdd.callOnClick()
                toast("请先选择客户")
            }

        }
        tvCustomerTelephone.addTextChangedListener {
            orderValue["contact_phone"] = it.toString()
        }
        btnCustomerArea.click {
            optionArea(supportFragmentManager) { province, city, county ->
                tvCustomerArea.text =
                    province?.name.orEmpty() + city?.name.orEmpty() + county?.name.orEmpty()
                orderValue["county_id"] = county?.id
                orderValue["city_id"] = city?.id
                orderValue["province_id"] = province?.id
            }
        }
        tvCustomerAddress.addTextChangedListener {
            orderValue["address"] = it.toString()
        }
        btnProductAdd.click {
            if (orderValue["customer_id"] == null) {
                toast("请先选择客户~")
                btnCustomerAdd.callOnClick()
                return@click
            }
            optionProduct(
                R.id.flCheckContent,
                supportFragmentManager,
                orderValue["customer_id"]?.toString()?.toIntOrNull(),
                selectedProducts
            ) {
                tvProducts.gone()
                selectedProducts.clear()
                selectedProducts.addAll(it)
                addProductItem(selectedProducts)
            }
        }
        btnDate.click {
            optionDatePickerSingle(this@WorkOrderCreateActivity) {
                orderValue["plan_at"] = it
                tvPlanDate.text = it
            }
        }
        btnServiceContent.click {
            optionReceiptContent(R.id.flCheckContent, supportFragmentManager) {
                orderValue["service_content"] = it
                tvReceiptType.text = it
            }
        }
        btnServiceType.click {
            optionReceiptTyp(R.id.flCheckContent, supportFragmentManager) {
                orderValue["service_type"] = it
                tvServiceType.text = it
            }
        }
        etMalfunctionIntroduction.addTextChangedListener {
            etMalfunctionIntroductionTip.text = "${it?.length ?: 0}/200"
            orderValue["description"] = it?.toString().orEmpty()
        }
        btnResponsibility.click {
            optionDeptUser(this@WorkOrderCreateActivity, "选择负责人") {
                orderValue["user_id"] = it.id
                tvResponsibility.gone()
                layoutResponsibility.visible()
                layoutResponsibility.tvName.text = it.realname.orEmpty()
            }
        }
        btnCollaboration.click {
            optionMultipleDeptUser(this@WorkOrderCreateActivity, "选择协作人", selectedCollaboration) {
                selectedCollaboration.clear()
                selectedCollaboration.addAll(it)
                addCollaborationItem(selectedCollaboration)
            }
        }
        btnImgAdd.click {
            picDialog(this@WorkOrderCreateActivity, pic = {
                launchPic("order" to "order_${System.currentTimeMillis()}.jpg") {
                    it.file?.let { it1 -> viewModel.uploadImg(it1) }
                }

            }, camera = {
                launchCamera("order" to "order_${System.currentTimeMillis()}.jpg") {
                    it.file?.let { it1 -> viewModel.uploadImg(it1) }
                }
            })
        }
        btnSingleSave.click {
            Log.i("打印", "initListener 提交: $orderValue")
            if (checkValue(false)) {
                //仅保存需要移除负责人和协同人
                orderValue["user_id"] = null
                orderValue["assist_user_ids"] = null
                viewModel.confirmOrder(orderValue)
            }
        }
        btnSaveDispatchOrder.click {
            if (checkValue(true))
                viewModel.confirmOrder(orderValue)
        }
    }

    private fun checkValue(isNeedUser: Boolean): Boolean {
        if (orderValue["customer_id"] == null) {
            toast("请选择客户~")
            return false
        }
        if (orderValue["contact_name"]?.toString().isNullOrEmpty()) {
            toast("请输入姓名~")
            return false
        }
        if (orderValue["contact_phone"]?.toString().isNullOrEmpty()) {
            toast("请输入电话~")
            return false
        }
        if (orderValue["province_id"] == null || orderValue["city_id"] == null || orderValue["county_id"] == null) {
            toast("请选择地区~")
            return false
        }
        if (orderValue["address"]?.toString().isNullOrEmpty()) {
            toast("请输入地址详细~")
            return false
        }
        if (selectedProducts.isEmpty()) {
            toast("请选择产品~")
            return false
        }

        if (orderValue["service_content"] == null) {
            toast("请选择服务内容~")
            return false
        }
        if (orderValue["service_type"] == null) {
            toast("请选择服务类型~")
            return false
        }
        if (isNeedUser) {
            if (orderValue["user_id"] == null) {
                toast("请选负责人~")
                return false
            }
        }
        return true

    }

    override fun ActivityWorkOrderCreateBinding.initIntent(intent: Any?) {
        when (intent) {
            is OrderCreateViewModel.ImgUploadIntent -> {
                addImageItem(intent.mode)
            }
            is OrderCreateViewModel.OrderCreateIntent -> {
                launch<WorkOrderDetailsActivity>("orderId" to intent.orderId)
                setResult(Activity.RESULT_OK)
                finish()
            }
        }
    }

    private fun addProductItem(products: ArrayList<ProductMode>) {
        bind.cgProducts.removeAllViews()
        orderValue["product_ids"] = products.map { it.id }
        products.forEach { mode ->
            val chip = ItemChipProductBinding.inflate(LayoutInflater.from(this)).root
            chip.text = "${mode.name}-${mode.model}"
            chip.setOnCloseIconClickListener {
                products.remove(mode)
                bind.cgProducts.removeView(chip)
                if (bind.cgProducts.childCount <= 0) {
                    bind.tvProducts.visible()
                }
                orderValue["product_ids"] = products.map { it.id }
            }
            bind.cgProducts.addView(chip)
        }
    }

    private fun addImageItem(file: UploadImgMode) {
        selectedImage.add(file)
        orderValue["images"] = selectedImage.map { it.path }
        if (bind.llImgContent.childCount >= 2) {
            bind.btnImgAdd.gone()
        }
        val itemBind = ItemImgBinding.inflate(LayoutInflater.from(this))
        itemBind.btnImgDelete.click {
            selectedImage.remove(file)
            orderValue["images"] = selectedImage.map { it.path }
            bind.llImgContent.removeView(itemBind.root)
            bind.btnImgAdd.visible()
        }
        Glide.with(this).load(file.url).into(itemBind.btnImg)
        bind.llImgContent.addView(itemBind.root, 0)
    }

    private fun addCollaborationItem(data: ArrayList<DeptUserMode>) {
        orderValue["assist_user_ids"] = data.map { it.id }
        bind.tvCollaboration.gone()
        bind.cgCollaboration.removeAllViews()
        data.forEach { mode ->
            val itemBind = ItemCollaborationBinding.inflate(LayoutInflater.from(this))
            itemBind.tvName.text = mode.realname.orEmpty()
            itemBind.root.click {
                bind.cgCollaboration.removeView(itemBind.root)
                data.removeAll { it.id == mode.id }
                orderValue["assist_user_ids"] = data.map { it.id }
                if (data.isEmpty()) {
                    bind.tvCollaboration.visible()
                }
            }
            bind.cgCollaboration.addView(itemBind.root)
        }
    }

    private fun ActivityWorkOrderCreateBinding.defaultEventDate(eventDetailsMode: EventDetailsMode) {
        orderValue["event_id"] = eventDetailsMode.id
        orderValue["contact_name"] = eventDetailsMode.contact_name.orEmpty()
        tvCustomerName.setText(eventDetailsMode.contact_name.orEmpty())
        orderValue["contact_phone"] = eventDetailsMode.contact_telephone.orEmpty()
        tvCustomerTelephone.setText(eventDetailsMode.contact_telephone.orEmpty())
        orderValue["description"] = eventDetailsMode.description.orEmpty()
        etMalfunctionIntroduction.setText(eventDetailsMode.description.orEmpty())
        orderValue["address"] = eventDetailsMode.address.orEmpty()
        tvCustomerAddress.setText(eventDetailsMode.address.orEmpty())
        eventDetailsMode.images?.forEach {
            addImageItem(UploadImgMode(path = it.image, url = it.img_url))
        }
    }
}